package org.cloud.scheduler.config;

import java.util.Iterator;
import java.util.List;

import org.cloud.scheduler.converter.StringToLongListConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
 * @author wangyuan
 * @since 2019年6月5日 下午5:40:22
 *
 */
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
	
	@Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        WebMvcConfigurer.super.configureMessageConverters(converters);
        
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = null;
        Iterator<HttpMessageConverter<?>> iterator = converters.iterator();
        HttpMessageConverter<?> converter = null;
        while(iterator.hasNext()) {
            converter = iterator.next();
            if(converter instanceof MappingJackson2HttpMessageConverter) {
                mappingJackson2HttpMessageConverter = (MappingJackson2HttpMessageConverter) converter;
                break;
            }
        }
        
        if(mappingJackson2HttpMessageConverter == null) {
            Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json();
            builder.indentOutput(true);
            builder.serializationInclusion(Include.NON_NULL);
            converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
        } else {
            ObjectMapper objectMapper = mappingJackson2HttpMessageConverter.getObjectMapper();
            objectMapper.setSerializationInclusion(Include.NON_NULL);
        }
    }
	
	@Override
    public void addFormatters(FormatterRegistry registry) {
        WebMvcConfigurer.super.addFormatters(registry);
        registry.addConverter(new StringToLongListConverter());
    }

}
